package cs342.uwosh.group1.mycontacts;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

import com.mycontacts.R;
import com.mycontacts.R.id;
import com.mycontacts.R.layout;
import com.mycontacts.R.menu;
import com.mycontacts.R.xml;

import cs342.uwosh.group1.mycontacts.Threads.CreateCategoryTask;
import cs342.uwosh.group1.mycontacts.Threads.GetAllContactTask;
import cs342.uwosh.group1.mycontacts.Threads.GetCategoryByIdTask;
import cs342.uwosh.group1.mycontacts.Threads.UpdateCategoryTask;
import cs342.uwosh.group1.mycontacts.Threads.UpdateContactTask;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;


public class CreateEditCategoryActivity extends PreferenceActivity {

	EditText nameOfCategory;
	String catName;
	
	static Context mainContext;
	
	int categoryId;
	PreferenceScreen target;
	ArrayList<Contact> contactsInCategory = new ArrayList<Contact>();
	SharedPreferences[] perfs;
	Category currentCategory;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	
		addPreferencesFromResource(R.xml.category_contact_pref);
		setContentView(R.layout.activity_create_edit_category);
		mainContext = this;
			
		
		Intent intent = getIntent();
		String categoryNumber = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
		categoryId = Integer.parseInt(categoryNumber);

		try {
			contactsInCategory = new GetAllContactTask().execute().get();
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		} catch (ExecutionException e1) {
			e1.printStackTrace();
		}

        target = (PreferenceScreen)findPreference("checkbox_pref");
        
		
		for(int i = 0; i < contactsInCategory.size(); i++)
		{
			CheckBoxPreference checkBoxPreference = new CheckBoxPreference(this);
	        
	        checkBoxPreference.setTitle(""+contactsInCategory.get(i).getName());
	        checkBoxPreference.setKey(""+ contactsInCategory.get(i).getId());
	        
	        checkBoxPreference.setLayoutResource(R.layout.custom_checkbox);
	        
	        if(contactsInCategory.get(i).getCategoryID() == categoryId)
	        {
	        	 checkBoxPreference.setChecked(true);
	        }
	        else
	        {
	        	 checkBoxPreference.setChecked(false);
	        }

	        target.addPreference(checkBoxPreference);
	        target.setWidgetLayoutResource(R.layout.custom_checkbox);
		}


		nameOfCategory = (EditText) findViewById(R.id.categoryNameEditText);
		
		if(!this.categoryExists(Integer.parseInt(categoryNumber))) // editing a category
		{
			currentCategory = new Category("Category " + categoryNumber);
		}
		else
		{
			try {
				currentCategory = new GetCategoryByIdTask().execute(null,categoryId,currentCategory).get();
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
		}
		nameOfCategory.setText(currentCategory.getCategoryName());
	}
	
	private void runChecks()
	{
		try {
			contactsInCategory = new GetAllContactTask().execute().get();
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		} catch (ExecutionException e1) {
			e1.printStackTrace();
		}

        target = (PreferenceScreen)findPreference("checkbox_pref");
        
		for(Contact contact: contactsInCategory)
		{
			if(contact.getCategoryID() == categoryId)
			{
				CheckBoxPreference temp = (CheckBoxPreference) target.findPreference(""+contact.getId());
	        	temp.setChecked(true);
			}
			else
			{
				CheckBoxPreference temp = (CheckBoxPreference) target.findPreference(""+contact.getId());
	        	temp.setChecked(false);	
			}
		}	
	}
	
	public void onResume()
	{
		super.onResume();
		runChecks();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_create_edit_category, menu);
		return true;
	}
	
	public void cancel(View view)
	{				
		this.finish();
	}
	
	public void saveCategory(View view)
	{
		
        SharedPreferences myPref= PreferenceManager.getDefaultSharedPreferences(this);

		for(Contact contact: contactsInCategory)
		{
	        boolean inCat = myPref.getBoolean(""+contact.getId(), false);
	        
	        if(inCat)
	        {
	        	contact.setCategoryID(categoryId);
	        	new UpdateContactTask().execute(contact);
	        }
	        else
	        {
	        	if(categoryId < MainActivity.db.categoryCount() && contact.getCategoryID() == categoryId)
	        	{
		        	contact.setCategoryID(0);
		        	new UpdateContactTask().execute(contact);
	        	}
	        }
	        CheckBoxPreference temp = (CheckBoxPreference) target.findPreference(""+contact.getId());
	        temp.setChecked(false);
			MainActivity.categoryViewed = categoryId;
		}
		
		if(!this.categoryExists(categoryId)) // editing a category
		{
			currentCategory.setCatagoryName(nameOfCategory.getText().toString());
			new CreateCategoryTask().execute(currentCategory);
		}
		else
		{
			currentCategory.setCatagoryName(nameOfCategory.getText().toString());
			new UpdateCategoryTask().execute(currentCategory);
		}
		
		MainActivity.categoryViewed = this.categoryId;

		MainActivity.changed = true;
		this.finish();
	}
	
	/**
	 * Used to determine whether a new category must be created, or if 
	 * a category is being edited.
	 * @param numberPassedToActivity The number passed into this class after a click 
	 * to create a new category, or a long click to edit a category.
	 * @return True if the numberPassedToActivity is not greater than the row count for the categories table.
	 */
	public boolean categoryExists(int numberPassedToActivity)
	{
		if(numberPassedToActivity > MainActivity.db.categoryCount())
		{
			return false;
		}
		else
		{
			return true;
		}
	}
		
}
